package Utils;

import Config.RegistryConfig;
import Config.RpcConfig;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.yaml.YamlUtil;

import java.io.InputStream;
import java.util.Map;

import static Constant.RpcConstant.RPC_REGISTRY_COFIG_PREFIX;

public class ConfigUtil {
    /**
     * 加载配置对象
     * @param tClass
     * @param prefix
     * @return
     */
    //todo 为了支持RpcConfig嵌套注册中心对象，这里采用RpcConfig字节码类
    public static RpcConfig loadConfig(Class<RpcConfig> tClass, String prefix) {
        return loadConfig(tClass, prefix, "");
    }

    /**
     * 加载配置对象，支持区分环境
     *
     * @param tClass
     * @param prefix
     * @param environment
     * @param <T>
     * @return
     */
    public static RpcConfig loadConfig(Class<RpcConfig> tClass, String prefix, String environment) {
        StringBuilder configFileBuilder = new StringBuilder("application");
        if (StrUtil.isNotBlank(environment)) {
            configFileBuilder.append("-").append(environment);
        }
        String yamlConfigFile = configFileBuilder.toString() + ".yaml";
        String ymlConfigFile = configFileBuilder.toString() + ".yml";
        String propertiesConfigFile = configFileBuilder.toString() + ".properties";

        //判断有没有yaml文件
        InputStream inputStream = ConfigUtil.class.getClassLoader().getResourceAsStream(yamlConfigFile);
        if(inputStream != null){
            Map<String,Object> yamlMap = YamlUtil.load(inputStream,Map.class);
            Map<String, Object> serverConfigMap = (Map<String, Object>) yamlMap.get(prefix);
            return BeanUtil.toBean(serverConfigMap,tClass);
        }
        //判断有没有yml文件
        inputStream = ConfigUtil.class.getClassLoader().getResourceAsStream(ymlConfigFile);
        if(inputStream != null){
            Map<String,Object> ymlMap = YamlUtil.load(inputStream,Map.class);
            Map<String, Object> serverConfigMap = (Map<String, Object>) ymlMap.get(prefix);
            return BeanUtil.toBean(serverConfigMap,tClass);
        }
        //默认是properties文件,如果没有会报错,由上层调用者处理(默认初始化)
        Props props = new Props(propertiesConfigFile);
         //将基础属性映射到 RpcConfig
         RpcConfig rpcConfig = (RpcConfig)props.toBean(tClass, prefix);

        // 处理嵌套的 RegistryConfig
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(props.getStr(RPC_REGISTRY_COFIG_PREFIX + ".address"));
        registryConfig.setRegistry(props.getStr(RPC_REGISTRY_COFIG_PREFIX + ".registry"));
        registryConfig.setTimeout(props.getLong(RPC_REGISTRY_COFIG_PREFIX + ".timeout", 10000L));// 默认值 10000L
        registryConfig.setUserName(props.getStr(RPC_REGISTRY_COFIG_PREFIX + ".userName"));
        registryConfig.setPassword(props.getStr(RPC_REGISTRY_COFIG_PREFIX + ".password"));
        rpcConfig.setRegistryConfig(registryConfig);
        return rpcConfig;



    }


}



